package andev.schoolhelper.login;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import andev.aandroidlib.activity.ANetActivity;
import andev.schoolhelper.R;
import andev.schoolhelper.main.MainActivity;
import andev.schoolhelper.register.RegisterActivity;
import andev.schoolhelper.util.VolleyJSONRequest;

public class LoginActivity extends ANetActivity {
    private EditText etUsername, etPassword;
    /* Angus
     * 2015年7月15日 上午8:31:00
     * “注册”监听
     */
    private TextView tvRegister;
    /* Angus
     * 2015年7月15日 下午3:53:35
     * comments
     */
    private Button btnLogin;
    private String username, password;
    private VolleyJSONRequest jsonObjectRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        InitEditTexts();
        InitRegisterListener();
        InitLoginListener();
    }

    private void InitEditTexts() {
        etUsername = (EditText) findViewById(R.id.etUsername);
        etPassword = (EditText) findViewById(R.id.etPassword);
        SharedPreferences loginPreferences = getApplicationContext().getSharedPreferences("Login", Context.MODE_PRIVATE);
        username = loginPreferences.getString("username", "");
        password = loginPreferences.getString("password", "");

        etUsername.setText(username);
        etPassword.setText(password);
    }

    private void InitRegisterListener() {
        tvRegister = (TextView) findViewById(R.id.tvRegister);
        tvRegister.setClickable(true);
        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goActivityForResult(RegisterActivity.class);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            username = bundle.getString("username");
            password = bundle.getString("password");
            Login();
        }
    }

    private void InitLoginListener() {
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLogin.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        username = etUsername.getText().toString();
                        password = etPassword.getText().toString();
                        if ("".equals(username) || "".equals(password)) {
                            Toast toast;
                            toast = Toast.makeText(LoginActivity.this, "请输入用户名和密码", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                            return;
                        }
                        Login();
                    }

                });
    }

    private void Login() {
        RequestQueue requestQueue = getAppRequestQueue();
        String url = "http://angusphp.sinaapp.com/service/mobile_loginService.php";
        //"http://10.0.3.2:8080/AngusJSP/MobileLoginServlet";

        Map<String, String> params = new HashMap<String, String>();
        params.put("username", username);
        params.put("password", password);
        Log.i("---", username + ":" + password);
        jsonObjectRequest =
                new VolleyJSONRequest
                        (
                                Method.POST,
                                url,
                                params,
                                new Response.Listener<JSONObject>() {
                                    @Override
                                    public void onResponse(JSONObject response) {
                                        LoginIn(response);
                                    }
                                },
                                new Response.ErrorListener() {
                                    @Override
                                    public void onErrorResponse(VolleyError error) {
                                        Log.e("-----", error.getMessage(), error);
                                    }
                                }
                        );

        if (requestQueue != null && jsonObjectRequest != null) {
            requestQueue.add(jsonObjectRequest);
        }
    }

    /**
     * 2015年7月15日
     *
     * @param 登陆完毕操作
     * @throws Exception
     */
    private void LoginIn(JSONObject response) {
        try {
            if ("false".equals(response.getString("loginstatus"))) {
                Toast toast;
                toast = Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            } else {
                SharedPreferences loginPreferences = getApplicationContext().getSharedPreferences("Login", Context.MODE_PRIVATE);
                Editor editor = loginPreferences.edit();
                editor.putBoolean("bAlreadyLogin", true);
                editor.putString("username", username);
                editor.putString("password", password);
                editor.commit();

                loginPreferences = getApplicationContext().getSharedPreferences("UserInfo", Context.MODE_PRIVATE);
                editor = loginPreferences.edit();
                editor.putString("nickname", response.getString("nickname"));
                editor.putString("mail", response.getString("mail"));
                editor.putString("phone", response.getString("phone"));
                editor.putString("city", response.getString("city"));
                editor.putString("qq", response.getString("qq"));
                editor.putString("intro", response.getString("intro"));
                editor.commit();

                goActivity(MainActivity.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
